import NavBar from '@/components/NavBar'
import { List, DatePicker, Toast, Popup, Dialog } from 'antd-mobile'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { useEffect, useRef, useState } from 'react'
import {
  getProfile,
  updateProfile,
  updateAvatar,
} from '@/store/actions/profile'
import { logout } from '@/store/actions/login'
import dayjs from 'dayjs'
import EditInput from './components/EditInput'
import EditList from './components/EditList'
import { useNavigate } from 'react-router-dom'
export default function ProfileEdit() {
  const navigate = useNavigate()
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(getProfile())
  }, [dispatch])
  // 获取个人信息
  const profile = useSelector((state) => state.profile.profile)
  // 控制时间日期控件的显示
  const [birthdayVisible, setBirthdayVisible] = useState(false)

  // 提交修改后的数据去更新redux的数据
  const commit = async (name, value) => {
    await dispatch(updateProfile(name, value))
    Toast.show({
      icon: 'success',
      content: '修改成功',
    })
  }

  // 控制昵称和自我介绍的弹出层的显示状态
  const [inputVisible, setInputVisible] = useState({
    visible: false,
    type: '', // 控制修改是昵称还是自我介绍
  })
  // 关闭EditINput的弹层
  const changeInputVisibleHandle = () => {
    setInputVisible({
      visible: false,
      type: '',
    })
  }

  // 控制头像和性别的弹出层的显示状态
  const [listVisible, setListVisible] = useState({
    visible: false,
    type: '', // 控制修改是昵称还是自我介绍
  })
  // 关闭EditList的弹层
  const changeListVisibleHandle = () => {
    setListVisible({
      ...listVisible,
      visible: false,
    })
  }

  // 绑定文件上传的dom
  const uploadRef = useRef(null)
  // 定义一个数组来保存EditList操作的数据
  const config = {
    photo: [
      {
        // h5网页时无法拉取手机摄像头功能
        title: '拍照',
        onClick: () => {},
      },
      {
        title: '本地选择',
        onClick: () => {
          // 触发本地文件上传
          uploadRef.current.click()
        },
      },
    ],
    gender: [
      {
        title: '男',
        onClick: async () => {
          await commit('gender', 0)
          changeListVisibleHandle()
        },
      },
      {
        title: '女',
        onClick: async () => {
          await commit('gender', 1)
          changeListVisibleHandle()
        },
      },
    ],
  }

  // 上传图片
  const uploadPhoto = async (e) => {
    // 获取上传的文件对象
    const file = e.target.files[0]
    // 相关的校验(必须是图片类型、大小限制)
    // formData可以携带二进制流数据
    const fd = new FormData()
    fd.append('photo', file)
    await dispatch(updateAvatar(fd))
    Toast.show({
      icon: 'success',
      content: '修改成功',
    })
    changeListVisibleHandle()
  }

  // 退出登录
  const doLogout = () => {
    // 提示框
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定要退出吗',
      confirmText: '确认退出',
      onConfirm: () => {
        // 调action的方法
        dispatch(logout())
        Toast.show({ icon: 'success', content: '退出成功', duration: 2000 })
        // 退出到登录页
        navigate('/login')
      },
    })
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人信息</NavBar>
        {/* 上传本地图片 */}
        <input
          onChange={uploadPhoto}
          ref={uploadRef}
          type="file"
          style={{ display: 'none' }}
        />
        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow
              onClick={() => {
                setListVisible({
                  visible: true,
                  type: 'photo',
                })
              }}
              extra={
                <span className="avatar-wrapper">
                  <img src={profile.photo} alt="" />
                </span>
              }
            >
              头像
            </List.Item>

            <List.Item
              arrow
              extra={profile.name}
              onClick={() => setInputVisible({ visible: true, type: 'name' })}
            >
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={
                <span className={!profile.intro ? 'intro' : ''}>
                  {profile.intro || '未填写'}
                </span>
              }
              onClick={() => setInputVisible({ visible: true, type: 'intro' })}
            >
              简介
            </List.Item>
          </List>

          {/* 列表二：显示性别、生日 */}
          <List className="profile-list">
            <List.Item
              onClick={() => {
                setListVisible({
                  visible: true,
                  type: 'gender',
                })
              }}
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
            >
              性别
            </List.Item>

            <DatePicker
              title="时间选择"
              visible={birthdayVisible}
              value={new Date(profile.birthday)}
              onClose={() => {
                setBirthdayVisible(false)
              }}
              max={new Date()}
              min={new Date(1900, 1, 1, 0, 0, 0)}
              onConfirm={async (val) => {
                //console.log(val)
                // 调用commit方法进行提交
                await commit('birthday', val)
                // 关闭选择器
                setBirthdayVisible(false)
              }}
            ></DatePicker>
            <List.Item
              arrow
              extra={dayjs(profile.birthday).format('YYYY-MM-DD')}
              onClick={() => setBirthdayVisible(true)}
            >
              生日
            </List.Item>
          </List>
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={doLogout}>
            退出登录
          </button>
        </div>
      </div>

      {/* 修改昵称和自我介绍的弹层(抽屉)  */}
      <Popup
        visible={inputVisible.visible}
        position="right"
        bodyStyle={{ width: '100vw' }}
      >
        {/* 这是要显示的抽屉的内容 */}
        <EditInput
          // 用于判断是昵称还是简介
          inputVisible={inputVisible}
          // 隐藏弹出
          changeVisible={changeInputVisibleHandle}
          // 提交修改
          commitUpdate={commit}
        ></EditInput>
      </Popup>

      {/* 修改头像和性别的弹层(抽屉)  */}
      <Popup
        visible={listVisible.visible}
        position="bottom"
        bodyStyle={{ height: '40vh' }}
        // 点击蒙版关闭
        onMaskClick={() => {
          changeListVisibleHandle()
        }}
      >
        {/* 这是要显示的抽屉的内容 */}
        <EditList
          changeListVisibleHandle={changeListVisibleHandle}
          config={config}
          type={listVisible.type}
        ></EditList>
      </Popup>
    </div>
  )
}
